package com.t.bricks.bussiness.db.dao.vacation.impl;

import java.util.Arrays;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import com.t.bricks.bussiness.db.dao.vacation.VacationDao;
import com.t.bricks.bussiness.db.entity.vacation.Vacation;
import com.t.bricks.bussiness.db.mapper.vacation.VacationMapper;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;

@Repository
public class VacationDaoImpl implements VacationDao<Vacation> {
	
	@Autowired
	private VacationMapper vacationMapper;

	@Value("${app.findPage.dLikeDate:配置文件中的当前库全文检索时间范围dLikeDate未设置}")
	private String sLikeDate;

	/**
	 * 检查待新增内容是否存在重复数据
	 * @param vacationData
	 * @return MsgEmity
	 */
	@Override
	public MsgEmity checkRepeatByAdd(Vacation vacationData) {
		int i = 0;
		try {
			i = vacationMapper.checkRepeatByAdd(vacationData);
			if (0 == i) {
				return new MsgEmity(false, "查询成功！没发现重复", 7007);
			}
		} catch (Exception e) {
			Log.error("检查待新增内容是否存在重复数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询失败，请查看异常日志", 7008);
		}
		
		return new MsgEmity(true, "查询成功！发现重复", i);//将查询到的数量(或sql中的构造码)返回以便特殊业务要求
	}

	/**
	 * 修改状态
	 * @param vacation
	 * @return MsgEmity 返回执行情况
	 */
	@Override
	public MsgEmity changeState(Vacation vacation) {
		try {
			int i = vacationMapper.changeState(vacation);
			if (i < 1) {
				MsgEmity me = this.getValueByFieldName(vacation.getsId(), Arrays.asList("iState", "iVersion"), false);
				if (!me.isSuccess()) {
					return me.appendDataCode(100);
				}
				
				Map<String, Object> map = me.getData();//如果影响数小于1,则检查数据
				if (null == map) {
					return new MsgEmity(false, "没有找到对应数据！", 7001);//删除影响数失败,但数据也不存在则视为成功
				}
				
				if (vacation.getiVersion() != Integer.valueOf(map.get("iVersion").toString()).intValue()) {
					return new MsgEmity(false, "更新状态失败，系统中的数据可能已经被更新！", 7002);
				}
				
				if (vacation.getiState() >= 0 && vacation.getiState() < Integer.valueOf(map.get("iState").toString()).intValue()) {
					return new MsgEmity(false, "更新状态失败，状态禁止逆操作！", 7003);
				}

				Log.error("更新状态未能得到预期影响值(预期1):", i);
				return new MsgEmity(false, "更新状态数据失败！", 7004);
			}
		} catch (Exception e) {
			Log.error("更新状态时发生异常:", e.getMessage());
			return new MsgEmity(false, "更新状态失败！", 7005);
		}
		
		return new MsgEmity(true, "更新状态成功！", 7999);
	}

}
